/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.wicket;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.util.value.ValueMap;
import org.apache.wicket.markup.html.WebPage;

/**
 *
 * @author OLYA
 */
public final class SignIn extends WebPage {

    public SignIn() {
        this(null);
    }
    
    public SignIn(PageParameters params) {
        // Create feedback panel and add to page
        final FeedbackPanel feedback = new FeedbackPanel("feedback");

        SignInSession session = (SignInSession)getSession();
        if(session.getUserName()!=null)
        {
            setResponsePage(getApplication().getHomePage());
        }
        
        add(feedback);

        // Add sign-in form to page, passing feedback panel as validation error
        // handler
        add(new SignInForm("signInForm"));
    }
    
    
    public final class SignInForm extends Form
    {
        // El-cheapo model for form
        private final ValueMap properties = new ValueMap();

        /**
         * Constructor
         * 
         * @param id
         *            id of the form component
         */
        public SignInForm(final String id)
        {
            super(id);

            // Attach textfield components that edit properties map model
            add(new TextField<String>("username", new PropertyModel<String>(properties, "username")));
            add(new PasswordTextField("password", new PropertyModel<String>(properties, "password")));
        }

        /**
         * @see org.apache.wicket.markup.html.form.Form#onSubmit()
         */
        @Override
        public final void onSubmit()
        {
            // Get session info
            SignInSession session = (SignInSession)getSession();            

            // Sign the user in
            if (session.authenticate(properties.getString("username"),
                properties.getString("password")))
            {
                if (!continueToOriginalDestination())
                {
                    setResponsePage(getApplication().getHomePage());
                }
            }
            else
            {
                // Form method that will notify feedback panel
                // Try the component based localizer first. If not found try the
                // application localizer. Else use the default
                final String errmsg = getLocalizer().getString("loginError", this,
                    "Unable to sign you in");
                error(errmsg);
            }
        }
    }
}
